import random
from urllib import request
from pyppeteer import launch
import cv2


async def get_dis():
    img = cv2.imread('image.png',0)
    template = cv2.imread('template.png',0)
    res = cv2.matchTemplate(img,template,cv2.TM_CCOEFF_NORMED)
    value = cv2.minMaxLoc(res)[2][0]
    print(value)
    dis = value * 342 / 360
    return dis


async def main(zh,user_name,password):
    print(zh,user_name,password)
    # order_datas = {'list':[{'ServiceOrderId': 544186, 'Id': 304713, 'BuyAccount': '企业账号', 'OrderCode': '248998845387'},{'ServiceOrderId': 544186, 'Id': 304713, 'BuyAccount': '企业账号', 'OrderCode': '248998845387'}]}
    while True:
        login = 1
        browser = await launch(headless = False,args=['--windows-size=1920,1080'])
        page = await browser.newPage()
        await page.setViewport({'width':1920,'height':1080})
        # 打开网页
        await page.goto('https://passport.jd.com/uc/login?ltype=logout&ReturnUrl=https%3A%2F%2Fdigital-ins.jd.com%2Frepair%2Ftask%2F1')
        # await page.click('div.login-tab-r')
        await page.waitFor(1000)
        # 输入账号密码
        await page.type('#loginname',user_name)
        await page.type('#nloginpwd', password)
        # 点击登录
        await page.click('div.login-btn')
        await page.waitFor(2000)
        for i in range(5):
            # 获取滑块图片
            try:
                img_src = await page.Jeval('.JDJRV-bigimg > img', 'el => el.src')
                request.urlretrieve(img_src, 'image.png')
                template_src = await page.Jeval('.JDJRV-smallimg > img', 'el => el.src')
                request.urlretrieve(template_src, 'template.png')
                await page.waitFor(2000)

                dis = await get_dis()
                el = await page.J('div.JDJRV-slide-btn')
                box = await el.boundingBox()
                await page.hover('div.JDJRV-slide-btn')

                await page.mouse.down()
                await page.mouse.move(box['x'] + dis + random.uniform(35, 36), box['y'], {'steps': 30})
                await page.waitFor(random.randint(300, 700))
                await page.mouse.move(box['x'] + dis + 30, box['y'], {'steps': 30})
                await page.mouse.up()
                await page.waitFor(2000)
                is_login = await page.xpath('//div[@class="shortcut_btn fore2"]')
                if is_login != []:
                    login = 0
                    break
                if i == 4:
                    await browser.close()
                    break
            except Exception as e:
                if ".JDJRV-bigimg > img" in str(e):
                    login = 0
                    break
                continue
        if login == 0:
            break
        else:
            continue
    await page.waitFor(5000)
    cookie = await page.cookies()
    await browser.close()
    return cookie
